package practise.线程池和lambca和stream流;

import java.util.Random;
import java.util.concurrent.*;

public class 案例三 {
    public static void main(String[] args) throws Exception {
//        创建可以同时执行三个线程的线程池
        ExecutorService executorService = Executors.newFixedThreadPool(3);

        Future<Double> f1 = executorService.submit(new MyCallable());   // 获得未来对象
        Future<Double> f2 = executorService.submit(new MyCallable());   //　向线程池添加线程
        Future<Double> f3 = executorService.submit(new MyCallable());

        double result = (f1.get()+f2.get()+f3.get())/3; // 通过未来对象，get到方法的返回结果
        System.out.println(result);

        executorService.shutdown(); // 关闭线程池，否则程序会一直运行

    }
}

class MyCallable implements Callable {
    static Random random = new Random();    // 随机数对象
    @Override
    public Double call() throws Exception {
        int sum = 10 ;
        int count = 0 ;
        for (int i = 0 ; i < 10 ; i++) {
            count += (random.nextInt(100)+1);   // 随机数 1~100
        }
        double avg = count / sum ;
        System.out.println(Thread.currentThread().getName()+"执行的averageNumber:"+avg);
        return avg;
    }
}